import axios from 'axios'

const baseURL = 'http://api.concord.sunnywing.com'

// GET方法，对应$fetch
export const fetchRequest = async (url: string, params?: any) => {
  try {
    const token = sessionStorage.getItem('token')
    const headers: Record<string, string> = {}
    
    if (token) {
      headers['token'] = token
    }
    
    const response = await axios({
      method: 'get',
      url: url.startsWith('http') ? url : baseURL + url,
      params: params,
      headers: headers
    })
    
    return response
  } catch (error) {
    console.error('Fetch request error:', error)
    return Promise.reject(error)
  }
}

// POST方法，对应$post
export const postRequest = async (url: string, data?: any) => {
  try {
    const token = sessionStorage.getItem('token')
    const headers: Record<string, string> = {
      'Content-Type': 'application/json'
    }
    
    if (token) {
      headers['token'] = token
    }
    
    const response = await axios({
      method: 'post',
      url: url.startsWith('http') ? url : baseURL + url,
      data: data,
      headers: headers
    })
    
    return response
  } catch (error) {
    console.error('Post request error:', error)
    return Promise.reject(error)
  }
}

// md5加密方法
export const md5 = (value: string) => {
  // 如果项目中有引入js-md5库，使用该库
  // 这里仅作占位，实际使用需要安装js-md5
  try {
    // 动态导入js-md5
    const md5Module = require('js-md5')
    return md5Module(value)
  } catch (error) {
    console.error('md5 function error:', error)
    return value // 失败时返回原值
  }
}

export default {
  fetchRequest,
  postRequest,
  md5
} 